package org.basket;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.basket.core.DBImportSAX;
import org.basket.core.DBManager;
import org.basket.core.UIManager;
import org.basket.core.UIManager.Page;
import org.basket.xml.XML;

public class BasketschedulerAdmin extends HttpServlet {
	private static final long serialVersionUID = 5881303186453666092L;
	private static final String TRUE = "true";
	private static final String LOGGEDON_ATTR = "loggedon";

	static {
		UIManager.addPage(BasketschedulerAdmin.class);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		final HttpSession session = request.getSession(true);
		response.setContentType("text/html; charset=UTF-8");
		final PrintWriter writer = response.getWriter();

		{
			String pass = (String) request.getParameter("password");
			final String adminPass = DBManager.getAdminPass();
			if (pass != null) {
				if (adminPass == null || (adminPass.equals(pass))) {
					session.setAttribute(LOGGEDON_ATTR, TRUE);
				}
			}
		}
		if (TRUE.equals(session.getAttribute(LOGGEDON_ATTR))) {
			final Page page = UIManager.getPage(this.getClass());
			page.setVar("postedtext", "");
			page.setVar("result_place", "");

			final String ops = request.getParameter("ops");
			if ("dump".equalsIgnoreCase(ops)) {
				doDump(page, request);
			} else if ("import".equalsIgnoreCase(ops)) {
				doImport(page, request);
			}
			page.render(writer);
		} else {
			writer.print("<center/><form method='POST' action=''><table border='0' cellspacing='0' cellpadding='0'><tr><td>Username:</td><td><input type='username' name='username' size='15' /></td></tr>" + "<tr><td>Password:</td><td><input type='password' name='password' size='15' /></td></tr>" + "<tr><td>&nbsp;</td><td><input type='submit' value='Login' /></td></tr>" + "</table></form>");
		}
	}

	private void doDump(Page page, HttpServletRequest request) {
		String postedText = request.getParameter("postedtext");
		page.setVar("postedtext", XML.escape(postedText));
		page.setVar("result_place", XML.escape(DBManager.DBExport()));
	}

	private void doImport(Page page, HttpServletRequest request) {
		String postedText = request.getParameter("postedtext");
		page.setVar("postedtext", XML.escape(postedText));
		try {
			DBImportSAX importDB = new DBImportSAX(postedText, true);
			importDB.parse();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		page.setVar("result_place", XML.escape(DBManager.DBExport()));
	}
}
